<%--
  Created by IntelliJ IDEA.
  User: pc2
  Date: 2020/5/28
  Time: 19:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String appContext = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + appContext;
%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>员工列表</title>
    <%--以/开始的相对路径,找资源,以服务器的路径为标准--%>
    <script type="text/javascript" src="<%=basePath%>/static/js/jquery-3.4.1.min.js"></script>
    <%--引入样式--%>
    <link href="<%=basePath%>/static/bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet">
    <script src="<%=basePath%>/static/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
</head>
<body>

<!-- AddModal -->
<div id="empAddModal" class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empName_add_input" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="empName_add_input" name="empName" placeholder="empName">
                            <span  class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="email_add_input" name="email" placeholder="email">
                            <span  class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <div class="checkbox">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="deptId" id="dept_add_select"></select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- EditModal -->
<div id="empUpdateModal" class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" >员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empName_add_input" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <p  class="form-control-static" id="empName_update_static"></p>
                            <span  class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="email_update_input" name="email" placeholder="email">
                            <span  class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <div class="checkbox">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="gender1_update_input" value="M" > 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="gender2_update_input" value="F"> 女
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="deptId" id="dept_update_select"></select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>


<%--搭建显示页面--%>
<div class="container">
    <%--标题--%>
    <div class="row">
        <div class="col=md-12">
            <h1>SSM-CRUD</h1>
        </div>
    </div>
    <%--按钮    --%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button type="button" class="btn btn-success" id="emp_add_modal_btn">新增</button>
            <button type="button" class="btn btn-danger" id="emp_delete_all_btn">删除</button>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <table id="emps_table" class="table table-hover">
                <thead>
                    <tr>
                        <th>
                            <input type="checkbox" id="check_all"/>
                        </th>
                        <th>#</th>
                        <th>员工姓名</th>
                        <th>性别</th>
                        <th>邮箱</th>
                        <th>部门</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>

            </table>
        </div>
    </div>

    <%--分页信息    --%>
    <div class="row">
        <%--记录数--%>
        <div class="col-md-6" id="page_info_area"></div>
        <div class="col-md-6" id="page_nav_area"></div>

    </div>
</div>

<script type="text/javascript">

    var totalRecord,currentPage;
    //1.页面加载完成以后,直接去发送ajax请求,要到分页数据
    $(function () {
        to_page(1)
    });

    function to_page(pn) {
        $.ajax({
            url: "<%=basePath%>/emp/getEmps",
            data: "pn="+pn,
            type: "get",
            success: function (result) {
                //console.log(result)
                //1.解析并显示员工数据
                build_emps_table(result)
                //2.解析并显示分页信息
                build_page_info(result)
                //3.解析显示分页条
                build_page_nav(result)
            }
        })
    }

    function build_emps_table(result) {
        //清空table表格
        $("#emps_table tbody").empty();
        var emps = result.extend.pageInfo.list;
        $.each(emps,function (index,item) {
            var checkBoxTd = $("<td><input type='checkbox' class='check_item'/></td>")
            var empIdTd = $("<td></td>").append(item.empId)
            var empNameTd = $("<td></td>").append(item.empName)
            var genderTd = $("<td></td>").append(item.gender == "M"?"男":"女")
            var emailTd = $("<td></td>").append(item.email)
            var deptNameTd = $("<td></td>").append(item.department.deptName)
            var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil").append("编辑"))
            //为编辑按钮添加一个自定义的属性,来表示当前员工的id
            editBtn.attr("edit-id",item.empId)
            var deleteBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash").append("删除"))
            deleteBtn.attr("del-id",item.empId);
            var btnTd  = $("<td></td>").append(editBtn).append(" ").append(deleteBtn)
            //append方法执行完成以后还是返回原来的元素
            $("<tr></tr>").append(checkBoxTd).append(empIdTd).append(empNameTd).append(genderTd).append(emailTd).append(deptNameTd)
                .append(btnTd).appendTo("#emps_table tbody")
        })

    }

    //解析显示分页信息
    function build_page_info(result) {
        $("#page_info_area").empty();
        $("#page_info_area").append("当前第"+result.extend.pageInfo.pageNum+"页,总共"+
            result.extend.pageInfo.pages+"页,总共"+result.extend.pageInfo.total+"条记录")
        totalRecord = result.extend.pageInfo.total;
        currentPage = result.extend.pageInfo.pageNum;
    }

    //解析显示分页条,而且点击有反应
    function build_page_nav(result) {
        $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"))
        if(result.extend.pageInfo.hasPreviousPage == false ){
            firstPageLi.addClass("disabled")
            prePageLi.addClass("disabled")
        }else{
            //为元素添加点击翻页的事件
            firstPageLi.click(function () {
                to_page(1)
            })
            prePageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum-1)
            })
        }

        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"))
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
        if(result.extend.pageInfo.hasNextPage == false ){
            nextPageLi.addClass("disabled")
            lastPageLi.addClass("disabled")
        }else{
            nextPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum+1)
            })
            lastPageLi.click(function () {
                to_page(result.extend.pageInfo.pages)
            })
        }

        //添加首页和下一页的提示
        ul.append(firstPageLi).append(prePageLi)
        $.each(result.extend.pageInfo.navigatepageNums,function (index,item) {
            var numLi = $("<li></li>").append($("<a></a>").append(item))
            if(result.extend.pageInfo.pageNum == item){
                numLi.addClass("active")
            }
            numLi.click(function () {
                to_page(item)
            })
            ul.append(numLi);
        })
        ul.append(nextPageLi).append(lastPageLi)
        var navEle = $("<nav></nav>").append(ul)
        navEle.appendTo("#page_nav_area");
    }

    //清空表单数据和样式
    function reset_form(ele){
        $(ele)[0].reset();
        $(ele).find("*").removeClass("has-success has-error");
        $(ele).find(".help-block").text("");
    }

    $("#emp_add_modal_btn").click(function () {
        //1.清除表单数据(表单重置),dom对象才有,jQuery没有;2.清除表单样式
        reset_form("#empAddModal form")

        //获得部门信息
        getDepts("#dept_add_select");
        //弹出模态框
        $("#empAddModal").modal({
            backdrop: "static"
        })
    })

    function getDepts(ele) {
        $(ele).empty()
        $.ajax({
            url: "<%=basePath%>/dept/getDepts",
            type: "get",
            success: function (result) {
                //console.log(result)
                $.each(result.extend.depts,function () {
                   var optionEle = $("<option></option>").append(this.deptName).attr("value",this.deptId)
                    optionEle.appendTo(ele);
                });

            }
        })
    }

    //表单校验
    function validate_add_form(){
        //1.拿到校验的数据,使用正则表达式
        var empName = $("#empName_add_input").val();
        var regName = /(^[a-z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/;
        if(!regName.test(empName)){
            //alert("用户名可以使2-5位中文或者6-16位英文和数字的组合");
            show_validate_msg("#empName_add_input","error","用户名可以是2-5位中文或者6-16位英文和数字的组合");
            return false;
        } else if($("#emp_save_btn").attr("ajax-va")== "error"){
            show_validate_msg("#empName_add_input","error","用户名不可用");
        } else {
            show_validate_msg("#empName_add_input","success","");
        }
        var email = $("#email_add_input").val();
        var regEmail = 	/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if(!regEmail.test(email)){
            //alert("邮箱格式不正确")
            //清空样式
            show_validate_msg("#email_add_input","error","邮箱格式不正确");
            return false;
        }else{
            show_validate_msg("#email_add_input","success","");
        }
        return true;

    }

    //显示校验结果的提示信息
    function show_validate_msg(ele,status,msg){
        //清除当前元素的校验状态
        $(ele).parent().removeClass("has-success has-error")
        $(ele).next("span").text("")
        if("success" ==status){
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text(msg)
        }else if("error" == status){
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg)
        }
    }

    //用户名校验重名
    $("#empName_add_input").change(function () {
        $(this).parent().removeClass("has-success has-error")
        $(this).next("span").text("")
        //发送ajax请求校验用户名是否可用
        var empName  = this.value;
        if(empName != "" & empName != null ){
            $.ajax({
                url: "<%=basePath%>/emp/checkUser",
                data: "empName="+empName,
                type: "POST",
                success: function (result) {
                    if(result.code == 100){
                        show_validate_msg("#empName_add_input","success","用户名可用");
                        $("#emp_save_btn").attr("ajax-va","success");
                    }else{
                        show_validate_msg("#empName_add_input","error",result.extend.va_msg);
                        $("#emp_save_btn").attr("ajax-va","error");

                    }
                }
            })
        }

    });

    //点击保存
    $("#emp_save_btn").click(function () {
        //1.模态框中填写的表单数据提交
        //先对要提交给服务器的数据进行校验
        if(!validate_add_form()){
            return false;
        }
        //判断之前的ajax用户名校验是否成功,如果成功,才发请求
        if ($(this).attr("ajax-va") == "error") {
            return false;
        }
        //2.发送ajax请求保存员工
        $.ajax({
            url: "<%=basePath%>/emp/saveEmp",
            type: "POST",
            data: $("#empAddModal form").serialize(),
            success:function (result) {
                //alert(result.msg)
                if(result.code == 100){
                    //员工保存成功
                    //1.关闭模态框
                    $("#empAddModal").modal('hide')
                    //2.来到最后一页,显示数据
                    //发送ajax请求
                    //
                    to_page(totalRecord)
                }else{
                    //console.log(result)
                    //显示失败信息
                    if(undefined != result.extend.errorFields.email){
                        show_validate_msg("#email_add_input","error","邮箱格式不正确");
                    }
                    if(undefined != result.extend.errorFields.empName){
                        show_validate_msg("#empName_add_input","error","用户名可以是2-5位中文或者6-16位英文和数字的组合");
                    }
                }

            }
        })
    })

    function getEmp(id){
        $.ajax({
            url: "<%=basePath%>/emp/getEmpInfo/"+id,
            type: "GET",
            success: function (result) {
                //console.log(result)
                var empData = result.extend.emp;
                $("#empName_update_static").text(empData.empName);
                $("#email_update_input").val(empData.email);
                $("#empUpdateModal input[name=gender]").val([empData.gender]);
                $("#dept_update_select").val([empData.deptId])
            }
        })
    }

    //编辑更新
    //使用on 绑定时间
    $(document).on("click",".edit_btn",function () {
        //1.查出部门信息,并显示部门列表
        getDepts("#dept_update_select")
        //2.查出员工信息,显示
        getEmp($(this).attr("edit-id"))
        //3.把员工的id传递给模态框的更新按钮
        $("#emp_update_btn").attr("edit-id",$(this).attr("edit-id"))
        //弹出模态框
        $("#empUpdateModal").modal({
            backdrop: "static"
        })
    })

    //点击更新,更新员工信息
    $("#emp_update_btn").click(function () {
        //1.验证邮箱是否格式正确
        var email = $("#email_update_input").val();
        var regEmail = 	/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if(!regEmail.test(email)){
            //alert("邮箱格式不正确")
            //清空样式
            show_validate_msg("#email_update_input","error","邮箱格式不正确");
            return false;
        }else{
            show_validate_msg("#email_update_input","success","");
        }

        //2.发送ajax请求,更新
        $.ajax({
            url: "<%=basePath%>/emp/updateEmp/"+$(this).attr("edit-id"),
            // type: "POST",
            // data: $("#empUpdateModal form").serialize()+"&_method=PUT",
            type: "PUT",
            data: $("#empUpdateModal form").serialize(),
            success: function (result) {
                //alert(result.msg)
                $("#empUpdateModal").modal('hide')
                //回到页面
                to_page(currentPage)
            }
        })
    })

    //单个删除
    $(document).on("click",".delete_btn",function () {
        //弹出确认删除对话框
        var empName = $(this).parents("tr").find("td:eq(2)").text();
        var empId = $(this).attr("del-id")
        if(confirm("确认删除["+empName+"]吗?")){
            //确认,发送删除请求
            $.ajax({
                url: "<%=basePath%>/emp/deleteEmpById/"+empId,
                type: "DELETE",
                success: function (result) {
                    alert(result.msg)
                    //回到本页
                    to_page(currentPage)
                }
            })
        }

    })

    //完成全选
    $("#check_all").click(function () {
        //attr获取checked是undefined
        //我们用dom原生的属性,attr获取自定义属性的值
        // prop修改和读取dom原生属性的值
        $(".check_item").prop("checked",$(this).prop("checked"));
    })

    $(document).on("click",".check_item",function () {
        //判断当前选中的元素是否选满
        var flag = $(".check_item:checked").length == $(".check_item").length;
        $("#check_all").prop("checked",flag)
    });

    //点击全部删除,批量删除
    $("#emp_delete_all_btn").click(function () {

        var empNames = "";
        var del_idstr = "";
        $.each($(".check_item:checked"),function () {
            empNames += $(this).parents("tr").find("td:eq(2)").text()+",";
            //组装id字符串
            del_idstr += $(this).parents("tr").find("td:eq(1)").text()+"-";
        })
        //去除empNames多余的逗号
        empNames = empNames.substring(0,empNames.length-1);
        //去除id多余的-
        del_idstr = del_idstr.substring(0,empNames.length-1);
        if (confirm("确认删除{"+empNames+"]吗?")){
            //发送ajax请求删除
            $.ajax({
                url: "<%=basePath%>/emp/deleteEmpById/"+del_idstr,
                type: "DELETE",
                success: function (result) {
                    alert(result.msg)
                    //回到本页
                    to_page(currentPage)
                }
            })
        }
    })

</script>

</body>

</html>
